package com.pic.mgt.haishin;

import com.pic.mgt.executer.UnitDispatchException;
import com.pic.mgt.executer.UnitDispatcher;
import com.pic.mgt.executer.UnitExecuter;
import com.pic.mgt.haishin.executer.HaishinBusinessUnitExecuter;
import com.pic.mgt.haishin.unit.AppointedHaishinBusinessUnit;
import com.pic.mgt.haishin.unit.GeneralHaishinBusinessUnit;
import com.pic.mgt.log.IgxLog;
import com.pic.mgt.unit.Unit;

/**
 * [業務執行分派]
 * 將配信業務根據其配信類別,送給不同的執行器(UnitExecuter)執行。
 * @author 洪政緯
 *
 */
public final class HaishinBusinessUnitDispatcher extends UnitDispatcher {
	private UnitExecuter appointedHaishinBusinessUnitExecuter;
	private UnitExecuter generalHaishinBusinessUnitExecuter;
	
	@Override
	public void execute(Unit haishinBusinessUnit) {
		// 指示配信
		if (AppointedHaishinBusinessUnit.class.isInstance(haishinBusinessUnit)) {
			// ********************** Log **********************
			if (IgxLog.messageLog.isDebugMode()) {
				IgxLog.messageLog.debug(this, 
						"Dispatching unit '{}' to appointed haishin business unit executer.",
						haishinBusinessUnit.getUnitName());
			}
			// ********************** Log **********************
			
			this.appointedHaishinBusinessUnitExecuter.execute(haishinBusinessUnit);
		}
		// 一般配信
		else if (GeneralHaishinBusinessUnit.class.isInstance(haishinBusinessUnit)) {
			// ********************** Log **********************
			if (IgxLog.messageLog.isDebugMode()) {
				IgxLog.messageLog.
					debug(this, "Dispatching unit '{}' to general haishin business unit executer.",
							haishinBusinessUnit.getUnitName());
			}
			// ********************** Log **********************
			
			this.generalHaishinBusinessUnitExecuter.execute(haishinBusinessUnit);
		}
		else {
			try {
				throw new UnitDispatchException(
						"SUDA-251 Dispatcher can't find match executer for unit '" +
						haishinBusinessUnit.getClass().getName() + "'.");
			} catch (UnitDispatchException e) {
				// ********************** Log **********************
				IgxLog.messageLog.error(this, e.getMessage());
				// ********************** Log **********************
			}
		}
	}
	
	@Override
	protected boolean adoptQueueService() {
		// 不需要使用 Queue Service。因為此 Dispatcher 會被排程器 (Scheuder)
		// 的Job所呼叫，而一個 Job 啟動時,本身就已經是一個 Thread ，因此不需再使用 Queue Service。
		return false;
	}
	
	// --- getter and setter ---

	public void setAppointedHaishinBusinessUnitExecuter(HaishinBusinessUnitExecuter appointedHaishinBusinessUnitExecuter) {
		this.appointedHaishinBusinessUnitExecuter = appointedHaishinBusinessUnitExecuter;
	}

	public void setGeneralHaishinBusinessUnitExecuter(HaishinBusinessUnitExecuter generalHaishinBusinessUnitExecuter) {
		this.generalHaishinBusinessUnitExecuter = generalHaishinBusinessUnitExecuter;
	}
}
